from flask import render_template, session, current_app, g, abort, jsonify, request

from info import constants, db
from info.models import User, News, Comment, CommentLike
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blu


@news_blu.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注的用户信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据库失败")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查询到用户数据")

    # 根据不同操作做不同逻辑
    if action == "follow":
        if target_user not in g.user.followed:
            # 当前用户关注列表增加一个值
            g.user.followed.append(target_user)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前用户已被关注")

    else:
        if target_user in g.user.followed:
            # 当前用户关注列表删除一个值
            g.user.followed.remove(target_user)
        else:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前用户未被关注")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route('/comment_like', methods=["POST"])
@user_login_data
def set_comment_like():
    """点赞
   1.获取数据
   2.对数据进行判断
   3.判断评论是否存在
   4.点赞和取消点赞
   :return:
   """

    # 1.获取数据
    user = g.user

    # 判断用户是否登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录！')

    news_id = request.json.get('news_id')
    # 评论id
    comment_id = request.json.get('comment_id')
    # add(点赞)，remove(取消点赞)
    action = request.json.get('action')

    # 2.判断数据
    if not all([news_id, comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误！')

    if action not in ['add', 'remove']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误！')

    try:
        news_id = int(news_id)
        comment_id = int(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='类型参数错误！')

    # 3.判断评论是否存在
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误！')

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg='无数据！')

    # 4.点赞和取消点赞
    if action == "add":
        # 点赞
        # 初始化点赞模型
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = g.user.id
            db.session.add(comment_like)
            # 增加点赞条数
            comment.like_count += 1
    else:
        # 删除点赞数据
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=g.user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            # 减小点赞条数
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")

    # 5.响应
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blu.route('/news_comment', methods=['POST'])
@user_login_data
def news_comment():
    """评论接口
    1.获取数据
    2.判断数据
    3.查询评论新闻是否存在
    4.初始化评论模型，对其赋值
    :return:
    """
    # 1.获取数据
    user = g.user
    # 判断用户是否登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录！')

    news_id = request.json.get('news_id')
    comment_content = request.json.get('comment')
    parent_id = request.json.get('parent_id')

    # 2.判断数据
    if not all([news_id, comment_content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误！')

    try:
        news_id = int(news_id)
        if parent_id:
            parent_id = int(parent_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='类型参数错误！')

    # 3.查询评论新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误！')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='无数据！')

    # 4.初始化评论模型，对其赋值
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news_id
    comment.content = comment_content
    if parent_id:
        comment.parent_id = parent_id

    # 添加到数据库
    # 为什么要自己使用commit， 因为return的时候就要把comment的id传过去
    # 使用SQLALCHEMY_COMMIT_ON_TEARDOWN，是在return之后调用的
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DATAERR, errmsg='数据错误！')

    # 5.响应
    return jsonify(errno=RET.OK, errmsg='操作成功！', data=comment.to_dict())


@news_blu.route('/news_collect', methods=['POST'])
@user_login_data
def news_collect():
    """收藏接口
    1.获取数据
    2.判断数据
    3.查询收藏新闻是否存在
    4.收藏和取消收藏
    :return:
    """

    # 1.获取数据
    user = g.user
    # 判断用户是否登录
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录！')

    news_id = request.json.get('news_id')
    # 用户是否收藏，两个值 收藏：'collect', 取消收藏：'cancel_collect'
    action = request.json.get('action')

    # 2.判断数据
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误！')

    if action not in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.PARAMERR, errmsg='收藏参数错误！')

    try:
        news_id = int(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='类型参数错误！')

    # 3.查询收藏新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='数据错误！')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='无数据！')

    # 4.收藏和取消收藏
    if action == 'collect':
        # 收藏
        # 判断用户是否收藏过
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        # 取消收藏
        if news in user.collection_news:
            user.collection_news.remove(news)

    # 5.响应
    return jsonify(errno=RET.OK, errmsg='操作成功！')


@news_blu.route('/<int:news_id>')
@user_login_data
def news_detail(news_id):
    # 查询登录状态
    # user_id = session.get('user_id')
    # user = None  # type: User
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    user = g.user

    # 右侧点击排行模板渲染
    # 取出按浏览量从高到底顺序的数据
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())

    # 查询id对应的数据
    news = None  # type: News
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        abort(404)

    if not news:
        abort(404)

    # 点击量加一
    news.clicks += 1

    # 判断是否收藏该新闻，默认值为 false
    is_collected = False
    if user:
        # 判断用户是否收藏了，该新闻
        if news in user.collection_news:
            is_collected = True

    # 评论
    comments = []
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)


    comment_like_ids = []
    if g.user:
        try:
            # 查看当前用户在当前新闻里面都点赞了那些评论
            # 1.查询所有评论的id
            comment_ids = [comment.id for comment  in comments ]
            # 2.查询当前评论中，那些评论被当前登录用户点赞
            comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids), CommentLike.user_id == g.user.id).all()
            # 3.取到所有被点赞的评论id
            comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.error(e)

    comments_dict_li = []
    for comment in comments:
        comment_dict = comment.to_dict()
        # 代表没有点赞
        comment_dict['is_like'] = False
        # 判断当前遍历到的评论是否被当前登录用户点赞
        if comment.id in comment_like_ids:
            comment_dict['is_like'] = True

        comments_dict_li.append(comment_dict)

    # 当前登录用户是否关注当前新闻作者
    is_followed = False
    # if 当前新闻有作者　and 用户当前登录用户关注过这个作者
    if news.user and user:
        # 判断当前用户是否关注过该作者
        if news.user in user.followed:
            is_followed = True

    data = {
        "user": user.to_dict() if user else None,
        "news_dict_list": news_dict_list,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "comments": comments_dict_li,
        "is_followed": is_followed,
        "user_id": news.user_id
    }

    return render_template('news/detail.html', data=data)
